import React, { PureComponent } from 'react';
import { Form, Input, Select, notification, DatePicker } from 'antd';
import { connect } from 'dva';
import "./form.less"
import moment from "moment"
const { RangePicker } = DatePicker;
class ProjectForm extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            stage: [],
            standard: [],
            roadLevel: [],
            projectLevel: [],
            designSpeed: []
        }
        this.onConfirm = this.onConfirm.bind(this);
        this.reset = this.reset.bind(this)
    }
    onConfirm(params = {}) {
        let { project,mode,form,addProject,refresh,updateProjectInfo,treeContext } = this.props;
        if (mode == 'add') {
            return new Promise((resolve, reject) => {
                form.validateFields((error, values) => {
                    if (!error) {
                        addProject(values, (res) => {
                            this.reset()
                            if (refresh) {
                                refresh()
                            }
                            resolve(`项目${project.name}添加成功!`)
                            if (params.onSuccess) {
                                params.onSuccess(res);
                            }
                        }, (error) => {
                            if (params.onError) {
                                params.onError(error);
                            }
                            reject()
                        });
                    } else {
                        if (params.onError) {
                            params.onError(error);
                        }
                        reject()
                    }
                });
            })
        } else {
            return new Promise((resolve, reject) => {
                form.validateFields((error, values) => {
                    if (!error) {

                       updateProjectInfo(values, (res) => {

                            notification.info({ message: `项目${project.name}更新成功!`})
                            if (treeContext) {
                               treeContext.updateTreeNodeSelf('p' + project.id, { title: values.name, name: values.name })
                            }

                            if (params.onSuccess) {
                                params.onSuccess(res);
                            }

                            if (refresh) {
                                refresh()
                            }
                            resolve(`项目${project.name}更新成功!`)
                        }, (error) => {
                            if (params.onError) {
                                params.onError(error);
                            }
                            reject()
                        });
                    } else {
                        if (params.onError) {
                            params.onError(error);
                        }
                        reject()
                    }
                });
            })
        }

    }
    reset() {
        let { form } = this.props;
        let values = form.getFieldsValue()
        for (const key in values) {
            if (values.hasOwnProperty(key)) {
                if (!(key.toLowerCase().includes('id'))) {
                    values[key] = null
                }
            }
        }
        form.setFieldsValue(values)
    }
    init() {
        let { form } = this.props;
        form.resetFields()
    }
    async componentDidMount() {
        let { dictlist, project,mode,getProjectDetail,onLoaded } = this.props;
        if (onLoaded) {
           onLoaded(this);
        }
       
        if (project&&mode=='edit') {
            let res = await getProjectDetail({ id: project.id })
            this.setState({
                project: res ? res : null,
            })
        }

        this.setState({
            projectLevel: dictlist.filter(item => item.dictType == "project_level"),
            roadLevel: dictlist.filter(item => item.dictType == "road_level"),
            designSpeed: dictlist.filter(item => item.dictType == "design_speed"),
            stage: dictlist.filter(item => item.dictType == "design_stage"),
            standard: dictlist.filter(item => item.dictType == "design_standard")
        })
    }

    render() {
        const {
            form = {},
            mode = 'add',
            project,
            classes
        } = this.props;
        const dateFormat = 'YYYY/MM/DD';
        const { getFieldDecorator } = form;
        const { stage, standard, roadLevel, projectLevel, designSpeed } = this.state;
        return (
            <Form
                style={{ marginTop: "20px" }}
                labelCol={{ flex:"0 0 100px" }}
                wrapperCol={{ span: 16 }}
                labelAlign="right"
                className={classes?classes:""}
            >
                

                <Form.Item className="half" label='项目名称'>
                    {getFieldDecorator('name', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.name : undefined
                    })(
                        <Input placeholder='请输入项目名称' />
                    )}
                </Form.Item>


                <Form.Item className="half" label='项目地点'>
                    {getFieldDecorator('place', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.place : undefined
                    })(
                        <Input placeholder='请输入项目地点' />
                    )}
                </Form.Item>



                <Form.Item className="half" label='设计阶段'>
                    {getFieldDecorator('designStage', {
                        rules: [
                            { required: true, message: '设计阶段' }
                        ],
                        initialValue: mode == 'edit' && project ? project.designStage - 0 : undefined
                    })(
                        <Select placeholder="请选择设计阶段" showSearch filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }>
                            {
                                stage.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>

                <Form.Item className="half" label='设计标准'>
                    {getFieldDecorator('designStandard', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.designStandard - 0 : undefined
                    })(
                        <Select placeholder="请选择设计标准" showSearch filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }>
                            {
                                standard.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }
                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='公路等级'>
                    {getFieldDecorator('roadLevel', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.roadLevel - 0 : undefined
                    })(
                        <Select placeholder="请选择公路等级">
                            {
                                roadLevel.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }
                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='设计时速'>
                    {getFieldDecorator('designSpeed', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.designSpeed - 0 : undefined
                    })(
                        <Select placeholder="请选择设计时速">
                            {
                                designSpeed.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }
                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='项目等级'>
                    {getFieldDecorator('projectLevel', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.projectLevel - 0 : undefined
                    })(
                        <Select placeholder="请选择项目等级" >
                            {
                                projectLevel.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }
                        </Select>
                    )}
                </Form.Item>

                <Form.Item className="half" label='项目周期'>
                    {getFieldDecorator('projectYear', {
                        rules: [
                            { required: true, message: '项目周期' }
                        ],
                        initialValue: mode == 'edit' && project && project.startYear && project.endYear ? [moment(project.startYear), moment(project.endYear)] : null
                    })(
                        <RangePicker onChange={(a, b) => {
                            form.setFieldsValue({
                                startYear: new Date(a[0]),
                                endYear: new Date(a[1])
                            })
                        }} allowClear
                            format={dateFormat}
                        />
                    )}
                </Form.Item>
                <Form.Item className="half" label='起点方向'>
                    {getFieldDecorator('startPlace', {
                        rules: [
                            { required: true, message: '起点方向' }
                        ],
                        initialValue: mode == 'edit' && project ? project.startPlace : undefined
                    })(
                        <Input placeholder='请输入起点方向' />
                    )}
                </Form.Item>


                <Form.Item className="half" label='终点方向'>
                    {getFieldDecorator('endPlace', {
                        rules: [
                            { required: true, message: '终点方向' }
                        ],
                        initialValue: mode == 'edit' && project ? project.endPlace : ''
                    })(
                        <Input placeholder='请输入终点方向' />
                    )}
                </Form.Item>

                <Form.Item className={`half none`} label='开始年份'>
                    {getFieldDecorator('startYear', {
                        rules: [
                            { required: true, message: '开始年份' }
                        ],
                        initialValue: mode == 'edit' && project && project.startYear ? new Date(project.startYear).getFullYear() : ''
                    })(
                        <Input placeholder='开始年份' />
                    )}
                </Form.Item>


                <Form.Item className={`half none`} label='结束年份'>
                    {getFieldDecorator('endYear', {
                        rules: [
                            { required: true, message: '结束年份' }
                        ],
                        initialValue: mode == 'edit' && project && project.endYear ? new Date(project.endYear).getFullYear() : ''

                    })(
                        <Input placeholder='结束年份' />
                    )}
                </Form.Item>
                <div className="half"></div>
                {
                   mode != 'add'? <Form.Item label='ID' className="hide" style={mode == 'add' ? { display: 'none' } : {}}>
                    {getFieldDecorator('id', {
                        rules: [
                            { required: mode != 'add', message: '必填' }
                        ],
                        initialValue: mode == 'edit' && project ? project.id : ''
                    })(
                        <Input />
                    )}
                </Form.Item>:undefined
                }
            </Form>
        );
    }
}

export default connect(
    ({ dict: { dictlist }, }) => ({ dictlist }),
    dispatch => ({
        addProject: (values, onSuccess, onError) => dispatch({
            type: 'project/add',
            payload: {
                values,
                onSuccess,
                onError

            }
        }),
        getProjectDetail: (values) => dispatch({
            type: 'project/getProjectDetail',
            payload: values
        }),
        updateProjectInfo: (values, onSuccess, onError) => dispatch({
            type: 'project/updateProjectInfo',
            payload: {
                params: values,
                onSuccess,
                onError

            }
        })
    })
)(Form.create('project', {

})(ProjectForm));